import config from "./config.js";
import local from '../utils/localStorage';
/* 
    @parms url 接口地址
    @parms method 请求方式
    @parms data 参数
    @parms isUpload 默认false 是否上传
 */

const request = (url, method, data, isUpload = false) => {
  return new Promise((resolve, reject) => {
    if (!isUpload) {
      wx.request({
        url: config.baseURL + url,
        data: data,
        method: method,
        header: {
          'Content-Type': 'application/json; charset=utf-8',
          'token': local.get('token') || '',
          'UserAuth': 'user'
        },
        success: (res) => {
          if (res.data.code == 1) {
            resolve(res.data)
          } else if (res.data.code == 401) {
            //未登录
            wx.reLaunch({
              url: '/subcontract/Login/login/login'
            });
          } else {
            //其他返回
            getApp().showToast(res.data.msg)
            console.log(res);
            // getApp().showToast('系统错误!')
          }
        },
        fail(error) {
          reject(error)
        },
        complete() {
        }
      });
    } else {
      wx.uploadFile({
        url: config.baseURL + url,
        filePath: data,
        name: 'file',
        header: {
          'Content-Type': 'application/json; charset=utf-8',
          'token': local.get('token') || '',
        },
        success: (uploadFileRes) => {
          let parms = JSON.parse(uploadFileRes.data)
          console.log(parms);
          if (parms.code == 200 || parms.code == 1) {
            resolve(parms)
          } else if (parms.code == 1101) {
            getApp().showToast('视频存在不合规！')
          } else if (parms.code == 401) {
            //未登录
            wx.reLaunch({
              url: '/subcontract/Login/login/login'
            });
          } else {
            getApp().showToast(res.data.msg)
            // getApp().showToast('系统错误!')
            // 上传失败
          }
        },
        fail: (error) => {
          reject(error)
          // 上传失败
        },
      });
    }

  })
}

export default {
  request //向外暴露request
}